package cn.firstsoft.modules.workflow.web;

import java.io.Writer;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hsqldb.lib.StringUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springside.core.Constants;
import org.springside.core.commons.BusinessException;
import org.springside.core.utils.StrUtils;
import org.springside.modules.security.domain.UserSession;

import cn.firstsoft.firstframe.util.StorageUtil;
import cn.firstsoft.modules.workflow.WorkFlowUtil;
import cn.firstsoft.modules.workflow.domain.WorkflowDataSource;
import cn.firstsoft.modules.workflow.domain.WorkflowFile;
import cn.firstsoft.modules.workflow.domain.WorkflowFileattach;
import cn.firstsoft.modules.workflow.domain.WorkflowIntegration;
import cn.firstsoft.modules.workflow.service.logic.IntegrationK3Manager;
import cn.firstsoft.modules.workflow.service.logic.WorkflowDataSourceManager;
import cn.firstsoft.modules.workflow.service.logic.WorkflowFileManager;
import cn.firstsoft.modules.workflow.service.logic.WorkflowFileattachManager;
import cn.firstsoft.modules.workflow.service.logic.WorkflowFileinboxManager;
import cn.firstsoft.modules.workflow.service.logic.WorkflowFlowRightManager;
import cn.firstsoft.modules.workflow.service.logic.WorkflowFlowtypeManager;
import cn.firstsoft.modules.workflow.service.logic.WorkflowManager;
import cn.firstsoft.modules.workflow.service.logic.WorkflowOperationResultManager;
import cn.firstsoft.modules.workflow.vo.IntegrationForm;

public class IntegrationK3ManagerController
  extends WorkflowIntegrationManagerController
{
  private WorkflowFileattachManager workflowFileattachManager;
  private WorkflowFlowRightManager workflowFlowRightManager;
  private WorkflowDataSourceManager workflowDataSourceManager;
  private IntegrationK3Manager integrationK3Manager;
  private WorkflowOperationResultManager workflowOperationResultManager;
  private WorkflowFileManager workflowFileManager;
  private WorkflowFileinboxManager workflowFileinboxManager;
  private WorkflowManager workflowManager;
  private WorkflowFlowtypeManager workflowFlowtypeManager;
  private static final String POSTIL_VIEW2 = "/modules/workflow/workflowFile_connection_office.jsp";
  
  public void setWorkflowFileattachManager(WorkflowFileattachManager workflowFileattachManager)
  {
    this.workflowFileattachManager = workflowFileattachManager;
  }
  
  public void setWorkflowFlowRightManager(WorkflowFlowRightManager workflowFlowRightManager)
  {
    this.workflowFlowRightManager = workflowFlowRightManager;
  }
  
  public void setWorkflowOperationResultManager(WorkflowOperationResultManager workflowOperationResultManager)
  {
    this.workflowOperationResultManager = workflowOperationResultManager;
  }
  
  public void setWorkflowDataSourceManager(WorkflowDataSourceManager workflowDataSourceManager)
  {
    this.workflowDataSourceManager = workflowDataSourceManager;
  }
  
  public void setIntegrationK3Manager(IntegrationK3Manager integrationK3Manager)
  {
    this.integrationK3Manager = integrationK3Manager;
  }
  
  public void setWorkflowFileManager(WorkflowFileManager workflowFileManager)
  {
    this.workflowFileManager = workflowFileManager;
  }
  
  public void setWorkflowFileinboxManager(WorkflowFileinboxManager workflowFileinboxManager)
  {
    this.workflowFileinboxManager = workflowFileinboxManager;
  }
  
  public void setWorkflowManager(WorkflowManager workflowManager)
  {
    this.workflowManager = workflowManager;
  }
  
  public void setWorkflowFlowtypeManager(WorkflowFlowtypeManager workflowFlowtypeManager)
  {
    this.workflowFlowtypeManager = workflowFlowtypeManager;
  }
  
  public ModelAndView getK3Data(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    ModelAndView mav = null;
    
    Object objDS = request.getParameter("dataSource");
    Object key = request.getParameter("key");
    Object condition = request.getParameter("condition");
    Object formfieldId = request.getParameter("formfieldId");
    if ((objDS == null) || (key == null) || (formfieldId == null)) {
      return mav;
    }
    Integer DSId = Integer.valueOf(String.valueOf(objDS));
    WorkflowDataSource workflowDataSource = this.workflowDataSourceManager.getWorkflowDataSource(DSId);
    
    WorkflowIntegration workflowIntegration = new WorkflowIntegration();
    
    String Uri = request.getRequestURI() + "?" + request.getQueryString();
    request.setAttribute("requestAction", Uri);
    

    String sql = "";
    

    Map<String, String> k3ConfigMap = this.integrationK3Manager.hasK3DataConfigFromXml(String.valueOf(key));
    sql = (String)k3ConfigMap.get("sql");
    if ((condition != null) && (!StringUtil.isEmpty(String.valueOf(condition)))) {
      sql = this.integrationK3Manager.buildCondition(sql, String.valueOf(condition));
    }
    workflowIntegration.setSqlDetail(sql);
    if (!k3ConfigMap.containsKey("display_fields")) {
      throw new BusinessException("k3IntegrationK3Data.xml配置中没有配置display_fields");
    }
    workflowIntegration.setListDetail((String)k3ConfigMap.get("display_fields"));
    
    workflowIntegration.setWorkflowDataSource(workflowDataSource);
    workflowIntegration.setDisplayMode("2");
    workflowIntegration.setFormField(String.valueOf(formfieldId));
    if (k3ConfigMap.containsKey("search_fields")) {
      workflowIntegration.setCondition((String)k3ConfigMap.get("search_fields"));
    }
    mav = super.onBaseDataShow(request, response, workflowIntegration);
    return mav;
  }
  
  public ModelAndView getFormData(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    ModelAndView mav = new ModelAndView();
    Object formObj = request.getParameter("integrationForm");
    Object fileObj = request.getParameter("fileId");
    Object dataSourceObj = request.getParameter("dataSource");
    Object k3DataObj = request.getParameter("k3Data");
    if ((formObj == null) || (fileObj == null) || (dataSourceObj == null)) {
      return mav;
    }
    String formKey = String.valueOf(formObj);
    String fileId = String.valueOf(fileObj);
    String dataSourceId = String.valueOf(dataSourceObj);
    
    IntegrationForm integrationForm = getIntegrationForm(formKey);
    Map map = getDataMap(integrationForm, fileId, mav);
    if (k3DataObj != null)
    {
      String k3DataStr = String.valueOf(k3DataObj);
      String[] k3Keys = k3DataStr.split(",");
      for (String key : k3Keys)
      {
        String[] arr = key.split("\\|");
        if (arr.length >= 2)
        {
          String sql = (String)IntegrationK3Constants.getK3DataMap().get(arr[0]);
          

          List<Map> list = getK3BaseDataMap(dataSourceId, sql);
          request.setAttribute(arr[1], list);
        }
      }
    }
    List<IntegrationForm.IdsFromNameClass> idsFromNameList = integrationForm.getIdsFromNameList();
    StringBuilder sb = new StringBuilder();
    for (IntegrationForm.IdsFromNameClass idsFromNameClass : idsFromNameList)
    {
      String name = (String)map.get(idsFromNameClass.getKey());
      if (!org.apache.axis.utils.StringUtils.isEmpty(name)) {
        if (formKey != null)
        {
          String sql_ = idsFromNameClass.getSql().replace("?", name);
          Object[] resultArr = getK3BaseDataArray(dataSourceId, sql_);
          if (resultArr == null) {
            sb.append(" " + name + " ");
          } else if (resultArr.length <= 0) {
            sb.append(" " + name + " ");
          } else {
            request.setAttribute(idsFromNameClass.getTargetKey(), resultArr[0].toString());
          }
        }
      }
    }
    if (sb.length() > 0) {
      request.setAttribute("k3DataSynFlag", sb.toString() + " 和异构系统数据不一致");
    }
    UserSession user = getUserSession(request);
    String randomKeyValue = getRandomSaveKey();
    String randomKey = user.getId() + "_savekey_" + Math.random();
    
    request.setAttribute("savekey", randomKey);
    request.setAttribute(randomKey, randomKeyValue);
    request.getSession().setAttribute(randomKey, randomKeyValue);
    
    request.setAttribute("formData", map);
    request.setAttribute("dataSource", dataSourceId);
    
    return mav;
  }
  
  private Map getDataMap(IntegrationForm integrationForm, String fileId, ModelAndView mav)
    throws Exception
  {
    List<String> sqlFinalList = new ArrayList();
    

    List<String> sqlList = integrationForm.getSqlListFromFile();
    for (String sql : sqlList)
    {
      sql = sql.replace("?", fileId);
      sqlFinalList.add(sql);
    }
    Map map = this.integrationK3Manager.getSqlDataMap(sqlFinalList);
    

    sqlFinalList.clear();
    Object sqlListFileList = integrationForm.getSqlListFormFileList();
    for (String sql : (List<String>)sqlListFileList)
    {
      sql = sql.replace("?", fileId);
      sqlFinalList.add(sql);
    }
    List<Map> listList = this.integrationK3Manager.getSqlDataList(sqlFinalList);
    
    map.put("list", listList);
    
    mav.setViewName(integrationForm.getPage());
    return map;
  }
  
  public IntegrationForm getIntegrationForm(String formKey)
    throws Exception
  {
    IntegrationForm integrationForm = this.integrationK3Manager.hasFormDataConfigFromXML(formKey);
    return integrationForm;
  }
  
  public ModelAndView saveK3Data(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    ModelAndView mav = new ModelAndView("integrationK3ResultPage.jsp");
    Object keyObj = request.getParameter("key");
    Object saveKeyObj = request.getParameter("savekey");
    
    Object dataSourceIdObj = request.getParameter("dataSourceId");
    Object operationObj = request.getParameter("operationId");
    Object fileIdObj = request.getParameter("fileId");
    Object formFieldObj = request.getParameter("formFieldName");
    if ((keyObj == null) || (dataSourceIdObj == null) || (operationObj == null) || (dataSourceIdObj == null)) {
      return mav;
    }
    String randomKeyValue = null;
    String randomKey = null;
    String savekeyInSession = null;
    if (saveKeyObj == null)
    {
      this.logger.info("====没有设置防止刷新的设置！===");
    }
    else
    {
      randomKey = String.valueOf(saveKeyObj);
      Object savekeySessionObj = request.getSession().getAttribute(randomKey);
      Object saveKeyValueObj = request.getParameter(randomKey);
      if (savekeySessionObj == null)
      {
        this.logger.info("========sessionKey== null ===");
        request.setAttribute("message", "不要非正常刷新页面");
        request.setAttribute("errMsg", Boolean.valueOf(true));
        return mav;
      }
      if (saveKeyValueObj == null)
      {
        this.logger.info("====防止刷新的设置,缺少==randomKeyValue==");
      }
      else
      {
        savekeyInSession = String.valueOf(savekeySessionObj);
        randomKeyValue = String.valueOf(saveKeyValueObj);
        if (!randomKeyValue.equals(savekeyInSession))
        {
          this.logger.info("========pageKey==" + randomKeyValue + "===");
          this.logger.info("========sessionKey==" + savekeyInSession + "===");
          request.setAttribute("message", "不要非正常刷新页面");
          request.setAttribute("errMsg", Boolean.valueOf(true));
          request.getSession().removeAttribute(randomKey);
          return mav;
        }
      }
    }
    request.getSession().removeAttribute(randomKey);
    
    String dataSourceId = String.valueOf(dataSourceIdObj);
    Map<String, String> paramMap = getParamMap(request);
    
    Map map = this.integrationK3Manager.getFinalDataMap(String.valueOf(keyObj), Integer.valueOf(dataSourceId), paramMap);
    
    List<String> finalSQLList = (List)map.get("finalSql");
    Map genaralStrMap = (Map)map.get(String.valueOf(keyObj));
    
    Map<String, String> sqlResult = null;
    try
    {
      sqlResult = this.integrationK3Manager.executeSql(finalSQLList, Integer.valueOf(dataSourceId));
      this.workflowOperationResultManager.saveWorkflowOperationResult(String.valueOf(operationObj), String.valueOf(fileIdObj));
      
      request.setAttribute(String.valueOf(keyObj), genaralStrMap);
      request.setAttribute("sqlResultMap", sqlResult);
    }
    catch (Exception e)
    {
      throw e;
    }
    finally
    {
      sysOutInfo(finalSQLList, sqlResult);
    }
    request.setAttribute("message", "保存成功");
    mav.addObject("formFieldName", String.valueOf(formFieldObj));
    return mav;
  }
  
  private void sysOutInfo(List<String> finalSQLList, Map<String, String> sqlResult)
  {
    if (finalSQLList != null)
    {
      this.logger.info("============Sql");
      for (String subsqlTemp : finalSQLList) {
        this.logger.info(subsqlTemp);
      }
    }
    if (sqlResult != null)
    {
      this.logger.info("============Sql===result");
      Set<Map.Entry<String, String>> set = sqlResult.entrySet();
      for (Object it = set.iterator(); ((Iterator)it).hasNext();)
      {
        Map.Entry<String, String> entry = (Map.Entry)((Iterator)it).next();
        this.logger.info("【" + (String)entry.getKey() + "】" + (String)entry.getValue());
      }
    }
  }
  
  public Map<String, String> getParamMap(HttpServletRequest request)
  {
    Map<String, String> paramMap = new HashMap();
    Enumeration<String> params = request.getParameterNames();
    while (params.hasMoreElements())
    {
      String param = (String)params.nextElement();
      String pvalue = request.getParameter(param);
      
      paramMap.put(param, pvalue);
    }
    return paramMap;
  }
  
  private Object[] getK3BaseDataArray(String dataSourceId, String sql)
    throws Exception
  {
    Integer DSId = Integer.valueOf(dataSourceId);
    
    WorkflowDataSource workflowDataSource = this.workflowDataSourceManager.getWorkflowDataSource(DSId);
    WorkflowIntegration workflowIntegration = new WorkflowIntegration();
    workflowIntegration.setSqlDetail(sql);
    workflowIntegration.setWorkflowDataSource(workflowDataSource);
    
    Object[] resultArray = this.integrationK3Manager.getK3BaseDataArray(workflowIntegration);
    return resultArray;
  }
  
  private List<Map> getK3BaseDataMap(String dataSourceId, String sql)
    throws Exception
  {
    Integer DSId = Integer.valueOf(dataSourceId);
    
    WorkflowDataSource workflowDataSource = this.workflowDataSourceManager.getWorkflowDataSource(DSId);
    WorkflowIntegration workflowIntegration = new WorkflowIntegration();
    workflowIntegration.setSqlDetail(sql);
    workflowIntegration.setWorkflowDataSource(workflowDataSource);
    
    List<Map> resultArray = this.integrationK3Manager.getK3BaseDataMap(workflowIntegration);
    return resultArray;
  }
  
  public String getRandomSaveKey()
  {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddss");
    String date = sdf.format(new Date());
    String randomKey = "k3_save_" + date + Math.random();
    return randomKey;
  }
  
  public ModelAndView ajaxCheckFileno(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    StringBuilder sb = new StringBuilder();
    String fileno = request.getParameter("fileno");
    if (org.apache.commons.lang.StringUtils.isBlank(fileno))
    {
      sb.append("null");
    }
    else
    {
      Map map = new HashMap();
      map.put("fileno_s_eq", fileno);
      List<WorkflowFile> list = this.workflowFileManager.findWorkflowFile(map);
      if (list.size() > 0)
      {
        WorkflowFile workflowFile = (WorkflowFile)list.get(0);
        sb.append(workflowFile.getId());
        sb.append("$$");
        sb.append(workflowFile.getFileno());
      }
      else
      {
        sb.append("null");
      }
    }
    response.setContentType("text/plain;charset=UTF-8");
    Writer writer = response.getWriter();
    writer.write(sb.toString());
    writer.close();
    return null;
  }
  
  public ModelAndView show(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    ModelAndView mav = new ModelAndView("/modules/workflow/workflowFile_connection_show.jsp");
    Integer id = null;
    String fid = request.getParameter("id");
    String isRelation = request.getParameter("isrelation");
    if ((isRelation == null) || (!"true".equals(isRelation))) {
      id = new Integer(fid);
    }
    Integer fileinboxId = null;
    Integer fromId = null;
    String lastAction = "";
    String curId = "";
    Integer curfileId = null;
    try
    {
      fileinboxId = new Integer(request.getParameter("fileinboxId"));
    }
    catch (Exception e)
    {
      System.out.println(e.getMessage());
    }
    try
    {
      lastAction = request.getParameter("lastAction").trim();
    }
    catch (Exception localException1) {}
    try
    {
      curfileId = new Integer(request.getParameter("curId"));
    }
    catch (Exception localException2) {}
    UserSession userSession = getUserSession(request);
    WorkflowFile wf = this.workflowFileManager.getWorkflowFile(id);
    if (wf == null) {
      createPermException(request, "协同审批->公文->显示", null);
    }
    Map map = new HashMap();
    map.put("id_i_eq", String.valueOf(id));
    List workflowFileList = this.workflowFileManager.findWorkflowFile(map);
    List<WorkflowFile> list;
    if (workflowFileList.size() > 0)
    {
      WorkflowFile workflowFile = (WorkflowFile)workflowFileList.get(0);
      

      mav.addObject("wordprintAttachs", this.workflowFileManager.showWordPrintAttach(request, workflowFile));
      

      WorkFlowUtil.removeEmptyFile(workflowFile);
      
      this.workflowFileinboxManager.convertWorkflowFile(workflowFile);
      if ("".equals(this.workflowFlowtypeManager
        .getWorkflowTemplate(workflowFile, ""))) {
        saveMessage(request, 
        
          getMessage(request, "WorkflowFileManagerController_label6", "模板文件不存在，请联系系统管理员！"));
      }
      String content = this.workflowFlowtypeManager
        .getWorkflowTemplateContent(workflowFile, "");
      
      Pattern pattern = Pattern.compile("(<textarea.*?>)(.*?)(</textarea>)", 32);
      Matcher matcher = pattern.matcher(content);
      StringBuffer buffer = new StringBuffer();
      while (matcher.find()) {
        matcher.appendReplacement(buffer, "$1$3");
      }
      matcher.appendTail(buffer);
      content = buffer.toString();
      
      mav.addObject("dynamicForm", 
        this.workflowFlowtypeManager.getDynamicForm(workflowFile, content));
      WorkFlowUtil.removeEmptyFile(this.workflowFileManager.getWorkflowFile(id));
      mav.addObject("workflowFile", 
        this.workflowFileManager.getWorkflowFile(id));
      
      mav.addObject("canPrint", 
        Integer.valueOf(this.workflowFlowtypeManager.existWorkflowTemplate(workflowFile, "print")));
      
      UserSession user = getUserSession(request);
      String printer = "," + 
        workflowFile.getWorkflow().getSuperprinters() + ",";
      String userid = "," + user.getId() + ",";
      if ((workflowFile.getWorkflow().getSuperprinters() != null) && 
        (printer.indexOf(userid) > -1)) {
        mav.addObject("islookprintinfo", "true");
      }
      mav.addObject("currentFileinboxes", this.workflowFileinboxManager.findCurrentFileinbox(workflowFile.getId()));
      if ((workflowFile.getFromId() != null) && 
        (workflowFile.getFromId().intValue() != 0))
      {
        if (workflowFile.getFromType().intValue() < 3) {
          try
          {
            mav.addObject("relationFile", 
              this.workflowFileManager.getWorkflowFile(workflowFile.getFromId()));
          }
          catch (Exception e)
          {
            mav.addObject("relationFile", null);
          }
        }
        mav.addObject("relationFileId", StrUtils.getEncString(workflowFile.getFromId().toString()));
      }
      mav.addObject("isSuccess", Integer.valueOf(1));
      mav.addObject("printtemplates", this.workflowFlowtypeManager.findWordtemplateByType(workflowFile.getWorkflowFlowtype().getId(), Integer.valueOf(3)));
      Map filter = new HashMap();
      filter.put("workflowFileXXid_i_eq", workflowFile.getId());
      filter.put("type_i_eq", Integer.valueOf(0));
      Map orderMap = new HashMap();
      orderMap.put("id", "desc");
      List<WorkflowFileattach> workflowFileAttach = this.workflowFileattachManager.findWorkflowFileattach(filter, "", orderMap);
      Integer lastVersionAttachId = Integer.valueOf(-1);
      if (workflowFileAttach.size() > 0) {
        lastVersionAttachId = ((WorkflowFileattach)workflowFileAttach.get(0)).getId();
      }
      mav.addObject("lastVersionAttachId", lastVersionAttachId);
      


      list = this.workflowFileManager.findWorkflowFile(map);
    }
    else
    {
      saveMessage(request, 
        getMessage(request, "WorkflowFileManagerController_label7", "此文件可能已经被其他人删除！"));
      mav.addObject("isSuccess", Integer.valueOf(0));
    }
    return mav;
  }
  
  public ModelAndView postil(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    String retMav = "/modules/workflow/workflowFile_connection_office.jsp";
    

    ModelAndView mav = new ModelAndView(retMav);
    WorkflowFileattach workflowFileattach = null;
    String attachId = request.getParameter("attachId");
    workflowFileattach = this.workflowFileattachManager.getWorkflowFileattach(Integer.valueOf(attachId));
    
    mav.addObject("workflowFileattach", workflowFileattach);
    return mav;
  }
  
  public ModelAndView download(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    Integer id = new Integer(request.getParameter("id"));
    
    WorkflowFileattach workflowFileattach = this.workflowFileattachManager.getWorkflowFileattach(id);
    
    String fileName = workflowFileattach.getFilename();
    String lastFileName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
    

    String fileExt = workflowFileattach.getFileext();
    if (this.workflowFileattachManager.isInArray(lastFileName, new String[] { ".xlsx", ".pptx" }))
    {
      fileName = fileName.substring(0, fileName.length() - 1);
      if (fileExt.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
        fileExt = "application/vnd.ms-excel";
      } else if (fileExt.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
        fileExt = "application/vnd.ms-powerpoint";
      }
    }
    if (StorageUtil.exists(workflowFileattach.getServerfile()))
    {
      if (!workflowFileattach.getFileext().equalsIgnoreCase("text/html")) {
        response.setContentType(workflowFileattach.getFileext());
      }
      try
      {
        response.setContentLength(workflowFileattach.getFilesize().intValue());
      }
      catch (Exception localException) {}
      response.setHeader("Content-Disposition", "attachment; filename=" + new String(workflowFileattach.getFilename().getBytes("GBK"), "ISO-8859-1"));
      
      byte[] mFileBody = StorageUtil.readFileToByteArray(workflowFileattach.getServerfile());
      if ((("iWebOffice".equalsIgnoreCase(Constants.WEB_OFFICE_OCX)) || 
        ("iWebOffice2009".equalsIgnoreCase(Constants.WEB_OFFICE_OCX))) && 
        (mFileBody.length > 16) && (mFileBody[0] == 68) && 
        (mFileBody[1] == 73) && (mFileBody[2] == 82) && 
        (mFileBody[3] == 71))
      {
        byte[] newFileBody = new byte[mFileBody.length - 16];
        for (int i = 0; i < mFileBody.length - 16; i++) {
          newFileBody[i] = mFileBody[(i + 16)];
        }
        StorageUtil.download(newFileBody, 
          response.getOutputStream());
      }
      else
      {
        if ((workflowFileattach.getFileext().equalsIgnoreCase("text/html")) || (workflowFileattach.getFileext().equalsIgnoreCase("text/plain")))
        {
          String s = StorageUtil.readFile(workflowFileattach.getServerfile());
          Matcher m = Pattern.compile("(?i)(?s)<meta.*?\\s+?content=(['\"])text/html;\\s*?charset=(.*?)\\1.*?>").matcher(s);
          if (m.find()) {
            response.setCharacterEncoding(m.group(2).trim());
          } else {
            response.setCharacterEncoding(StorageUtil.getEncoding(workflowFileattach.getServerfile()));
          }
        }
        StorageUtil.download(workflowFileattach.getServerfile(), 
          response.getOutputStream());
      }
    }
    return null;
  }
  
  
  
  
  

  //======================二次开发F7支持多选====================================
  
  /**
   * 支持F7信息多选，回写！
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  public ModelAndView getK3DataEx(HttpServletRequest request, HttpServletResponse response)
		    throws Exception
		  {
		    ModelAndView mav = null;

		    Object objDS = request.getParameter("dataSource");
		    Object key = request.getParameter("key");
		    Object condition = request.getParameter("condition");
		    Object formfieldId = request.getParameter("formfieldId");

		    if ((objDS == null) || (key == null) || (formfieldId == null)) return mav;
		    Integer DSId = Integer.valueOf(String.valueOf(objDS));
		    WorkflowDataSource workflowDataSource = this.workflowDataSourceManager.getWorkflowDataSource(DSId);

		    WorkflowIntegration workflowIntegration = new WorkflowIntegration();

		    String Uri = request.getRequestURI() + "?" + request.getQueryString();
		    request.setAttribute("requestAction", Uri);

		    String sql = "";

		    Map k3ConfigMap = this.integrationK3Manager.hasK3DataConfigFromXml(String.valueOf(key));
		    sql = (String)k3ConfigMap.get("sql");
		    if ((condition != null) && (!StringUtil.isEmpty(String.valueOf(condition)))) {
		      sql = this.integrationK3Manager.buildCondition(sql, String.valueOf(condition));
		    }
		    workflowIntegration.setSqlDetail(sql);
		    if (!k3ConfigMap.containsKey("display_fields")) {
		      throw new BusinessException("k3IntegrationK3Data.xml配置中没有配置display_fields");
		    }

		    workflowIntegration.setListDetail((String)k3ConfigMap.get("display_fields"));

		    workflowIntegration.setWorkflowDataSource(workflowDataSource);
		    workflowIntegration.setDisplayMode("ex");

		    
		    workflowIntegration.setFormField(String.valueOf(formfieldId));
		    if (k3ConfigMap.containsKey("search_fields")) {
		      workflowIntegration.setCondition((String)k3ConfigMap.get("search_fields"));
		    }

		    mav = super.onBaseDataShow(request, response, workflowIntegration);
		    return mav;
		  }
  
  
  /**
   * 与k3数据保存共用数据
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  public ModelAndView saveK3DataEx(HttpServletRequest request, HttpServletResponse response)
		    throws Exception
		  {
//	        IntegrationForm integrationForm = getIntegrationForm(formKey);
//	        integrationForm.getPage();
//          http://localhost:7890/oa/modules/workflow/integrationK3.do?method=getFormData&integrationForm=integrationGoldhat&openwin=true&fileId=7&operationId=7&dataSource=1
	        //integrationGoldhat.jsp
	  
		    Object keyObj = request.getParameter("key");
		    Object saveKeyObj = request.getParameter("savekey");

		    Object dataSourceIdObj = request.getParameter("dataSourceId");
		    Object operationObj = request.getParameter("operationId");
		    Object fileIdObj = request.getParameter("fileId");
		    Object formFieldObj = request.getParameter("formFieldName");
		    String billstatue = request.getParameter("billstatue");
		    
		    String url="";
		    if(fileIdObj==null){
		    	url="integrationK3ResultPage.jsp";
		    }
		    ModelAndView mav = new ModelAndView(url);
		    //mav.setViewName("redirect:"+url);
		    //mav.setViewName("redirect:/modules/demo1/demoGood.do");
		    
		    if ((keyObj == null) || (dataSourceIdObj == null) || (operationObj == null) || (dataSourceIdObj == null)) return mav;

		    //当非空时，设置返回的url串。
	    	url="integrationK3.do?method=getFormDataEx&integrationForm="+keyObj+"&fileId="+URLEncoder.encode(fileIdObj.toString(),"utf-8")+"&openwin=true&dataSource="+dataSourceIdObj;//
	    	mav = new ModelAndView(url);
		    
		    String randomKeyValue = null;
		    String randomKey = null;
		    String savekeyInSession = null;

		    if (saveKeyObj == null) {
		      this.logger.info("====没有设置防止刷新的设置！===");
		    } else {
		      randomKey = String.valueOf(saveKeyObj);
		      Object savekeySessionObj = request.getSession().getAttribute(randomKey);
		      Object saveKeyValueObj = request.getParameter(randomKey);

		      if (savekeySessionObj == null) {
		        this.logger.info("========sessionKey== null ===");
		        request.setAttribute("message", "不要非正常刷新页面");
		        request.setAttribute("errMsg", Boolean.valueOf(true));
		        return mav;
		      }if (saveKeyValueObj == null) {
		        this.logger.info("====防止刷新的设置,缺少==randomKeyValue==");
		      } else {
		        savekeyInSession = String.valueOf(savekeySessionObj);
		        randomKeyValue = String.valueOf(saveKeyValueObj);

		        if (!randomKeyValue.equals(savekeyInSession)) {
		          this.logger.info("========pageKey==" + randomKeyValue + "===");
		          this.logger.info("========sessionKey==" + savekeyInSession + "===");
		          request.setAttribute("message", "不要非正常刷新页面");
		          request.setAttribute("errMsg", Boolean.valueOf(true));
		          request.getSession().removeAttribute(randomKey);
		          return mav;
		        }
		      }
		    }

		    request.getSession().removeAttribute(randomKey);

		    String dataSourceId = String.valueOf(dataSourceIdObj);
		    Map paramMap = getParamMap(request);

		    Map map = this.integrationK3Manager.getFinalDataMap(String.valueOf(keyObj), Integer.valueOf(dataSourceId), paramMap);

		    List finalSQLList = (List)map.get("finalSql");
		    Map genaralStrMap = (Map)map.get(String.valueOf(keyObj));

		    Map sqlResult = null;
		    try {
		      sqlResult = this.integrationK3Manager.executeSql(finalSQLList, Integer.valueOf(dataSourceId));
		      //this.workflowOperationResultManager.saveWorkflowOperationResult(String.valueOf(operationObj), String.valueOf(fileIdObj));
		      request.setAttribute(String.valueOf(keyObj), genaralStrMap);
		      request.setAttribute("sqlResultMap", sqlResult);
		    } catch (Exception e) {
		      throw e;
		    } finally {
		      sysOutInfo(finalSQLList, sqlResult);
		    }
		    request.setAttribute("message", "保存成功");
		    mav.addObject("formFieldName", String.valueOf(formFieldObj));
		    //返回页面信息处理
		    request.setAttribute("saveOK", "SUCCESS"); 
		    request.setAttribute("billstatue", billstatue);
		    return mav;
		  }
  
   /**
    * 因传参的url需要中文所以独立处理编码方式
    * @param request
    * @param response
    * @return
    * @throws Exception
    */
  public ModelAndView getFormDataEx(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    ModelAndView mav = new ModelAndView();
    Object formObj = request.getParameter("integrationForm");
    Object fileObj = request.getParameter("fileId");

    Object dataSourceObj = request.getParameter("dataSource");
    Object k3DataObj = request.getParameter("k3Data");

    
    if ((formObj == null) || (fileObj == null) || (dataSourceObj == null)) return mav;
    String formKey = String.valueOf(formObj);
    String fileId = String.valueOf(fileObj);
    fileId=URLDecoder.decode(fileId,"utf-8");
    String dataSourceId = String.valueOf(dataSourceObj);

    IntegrationForm integrationForm = getIntegrationForm(formKey);
    Map map = getDataMap(integrationForm, fileId, mav);

    if (k3DataObj != null) {
      String k3DataStr = String.valueOf(k3DataObj);
      String[] k3Keys = k3DataStr.split(",");
      for (String key : k3Keys) {
        String[] arr = key.split("\\|");
        if (arr.length < 2) {
          continue;
        }
        String sql = (String)IntegrationK3Constants.getK3DataMap().get(arr[0]);

        List list = getK3BaseDataMap(dataSourceId, sql);
        request.setAttribute(arr[1], list);
      }

    }

    List<IntegrationForm.IdsFromNameClass> idsFromNameList = integrationForm.getIdsFromNameList();
    StringBuilder sb = new StringBuilder();
    for (IntegrationForm.IdsFromNameClass idsFromNameClass : idsFromNameList) {
      String name = (String)map.get(idsFromNameClass.getKey());
      if (org.apache.axis.utils.StringUtils.isEmpty(name)) {
        continue;
      }
      if (formKey != null) {
        String sql_ = idsFromNameClass.getSql().replace("?", name);
        Object[] resultArr = getK3BaseDataArray(dataSourceId, sql_);
        if (resultArr == null)
          sb.append(" " + name + " ");
        else if (resultArr.length <= 0)
          sb.append(" " + name + " ");
        else {
          request.setAttribute(idsFromNameClass.getTargetKey(), resultArr[0].toString());
        }
      }
    }
    if (sb.length() > 0) {
      request.setAttribute("k3DataSynFlag", sb.toString() + " 和异构系统数据不一致");
    }

    UserSession user = getUserSession(request);
    String randomKeyValue = getRandomSaveKey();
    String randomKey = user.getId() + "_savekey_" + Math.random();

    request.setAttribute("savekey", randomKey);
    request.setAttribute(randomKey, randomKeyValue);
    request.getSession().setAttribute(randomKey, randomKeyValue);

    request.setAttribute("formData", map);
    request.setAttribute("dataSource", dataSourceId);
    request.setAttribute("fileId", fileId);
    
    return mav;
  }
}
